#include "CalculatorUI.h"
#include <QDebug>


CalculatorUI::CalculatorUI() : QWidget(NULL, Qt::WindowCloseButtonHint)
{
    m_cal = NULL;
}

bool CalculatorUI::construct()
{
    bool ret = true;

    const char* btnText[20] =
    {
        "7","8","9","+","(",
        "4","5","6","-",")",
        "1","2","3","*","<-",
        "0",".","=","/","C",

    };

    /* 创建行编辑器 */
    m_edit = new QLineEdit(this);

    if ( m_edit!=NULL )
    {
        m_edit->move(10,10);
        m_edit->resize(240,30);
        m_edit->setReadOnly(true);
        m_edit->setAlignment(Qt::AlignRight); // 设置右边对齐
    }
    else
    {
        ret = false;
    }

    /* 创建按钮4*5 */
    for (int i=0; (i<4)&&ret; i++) // 有4行
    {
        for (int j=0;j<5;j++) // 每行有5列
        {
            int k = 5*i+j;

             m_buttons[k] = new QPushButton(this);

             if (m_buttons[k]!=NULL)
             {
                m_buttons[k]->resize(40,40);
                m_buttons[k]->move(10+(10+40)*j,50+(10+40*i)); // 第一个按钮位置为(10,50), 按钮的横向和纵向空间都为10
                m_buttons[k]->setText(btnText[k]);

                connect(m_buttons[k],SIGNAL(clicked(bool)), this, SLOT(onButtonClicked()));
             }
             else
             {
                 ret = false;
             }
        }
    }

    return ret;
}

CalculatorUI *CalculatorUI::NewInstance()
{
    CalculatorUI* ret = new CalculatorUI();

    if ( ret == NULL || !ret->construct() )
    {
        delete ret;
        ret = NULL;
    }

    return ret;
}

void CalculatorUI::show()
{
    QWidget::show();
    setFixedSize(width(), height());
}

void CalculatorUI::onButtonClicked()
{
    QPushButton* btn = dynamic_cast<QPushButton*>(sender()); // 获取发送者(按键)

    if ( btn != nullptr )
    {
        QString clickText = btn->text();

        if(clickText=="<-")
        {
            QString text = m_edit->text();
            if (text.length()>0)
            {
                text.remove(text.length()-1,1);
                m_edit->setText(text);
            }
        }
        else if(clickText=="C")
        {
            m_edit->setText("");
        }
        else if(clickText=="=")
        {
            /* 使用接口,m_cal由上一级类指定设置 */
            if (m_cal!=NULL)
            {
                m_cal->expression(m_edit->text());
                m_edit->setText(m_cal->result());
            }
        }
        else
        {
            m_edit->setText(m_edit->text()+clickText);
        }
    }
}

ICalculator *CalculatorUI::getCalculator()
{
    return m_cal;
}

void CalculatorUI::setCalculator(ICalculator *cal)
{
    m_cal = cal;
}
